package cn.sc.summer.mybatis.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.sc.summer.constant.token.TokenConstant;
import cn.sc.summer.exception.exceptions.CommonException;
import cn.sc.summer.exception.hodler.SpringContextHolder;
import cn.sc.summer.token.po.UserDetailX;
import cn.sc.summer.token.util.UserUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户工具类
 *
 * @author a-xin
 */
public class MPUserUtil {

    /**
     * 获取登录用户
     *
     * @return LoginUserDTO
     */
    public static UserDetailX getLoginUser() {
       return UserUtil.getLoginUser(getLoginToken());
    }

    /**
     * 获取是否用户登录状态
     *
     * @return 是否登录
     */
    public static Boolean hasLoginStatus() {
        try {
            UserDetailX loginUser = getLoginUser();
            if (ObjectUtil.isNotNull(loginUser)) {
                return Boolean.TRUE;
            }
            return Boolean.FALSE;
        } catch (CommonException e) {
            return Boolean.FALSE;
        }
    }

    /**
     * 获取登录用户token
     *
     * @return token
     */
    public static String getLoginToken() {
        try {
            HttpServletRequest request = SpringContextHolder.getHttpServletRequest();
            String token = request.getHeader(TokenConstant.ACCESS_TOKEN);
            if (StrUtil.isBlank(token)) {
                throw new CommonException("Not logged in！");
            }
            return token;
        } catch (Exception e) {
            throw new CommonException("Not logged in: " + e.getMessage(), e);
        }
    }

}
